import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import { login as loginApi, getUserInfo } from '@/services/auth';
import type { LoginCredentials, User } from '@/services/auth';

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const token = ref<string>('');
  const role = ref<string>('');
  const user = ref<User | null>(null);
  const rememberMe = ref<boolean>(false);

  // 计算属性
  const isAuthenticated = computed(() => !!token.value);

  /**
   * 检查登录信息是否过期
   */
  function checkLoginExpiry(): boolean {
    const loginTimeStr = localStorage.getItem('loginTime');
    if (!loginTimeStr) return true;
    
    const loginTime = new Date(loginTimeStr).getTime();
    const now = Date.now();
    const oneDay = 24 * 60 * 60 * 1000; // 一天的毫秒数
    
    return now - loginTime > oneDay;
  }

  /**
   * 清除登录信息
   */
  function clearLoginInfo() {
    token.value = '';
    role.value = '';
    user.value = null;
    rememberMe.value = false;
    
    localStorage.removeItem('token');
    localStorage.removeItem('role');
    localStorage.removeItem('userData');
    localStorage.removeItem('rememberMe');
    localStorage.removeItem('loginTime');
  }
  
  // 方法
  async function login(credentials: LoginCredentials) {
    try {
      const response = await loginApi(credentials);
      
      // 检查response是否包含access_token和user字段
      if (response && response.access_token && response.user) {
        // 设置token和角色
        token.value = response.access_token;
        role.value = response.user.roles?.[0]?.name || 'user';
        rememberMe.value = credentials.rememberMe || false;
        
        // 存储登录信息到localStorage，设置过期时间为一天
        localStorage.setItem('token', token.value);
        localStorage.setItem('role', role.value);
        localStorage.setItem('userData', JSON.stringify(response.user));
        localStorage.setItem('rememberMe', rememberMe.value.toString());
        localStorage.setItem('loginTime', new Date().toISOString());
        
        // 获取用户信息
        user.value = response.user;
        
        return response;
      } else {
        const error = new Error('登录响应格式不正确');
        console.error('登录失败:', error);
        throw error;
      }
    } catch (error: any) {
      console.error('登录失败:', error);
      // 保留原始错误的详细信息
      throw error;
    }
  }

  
  async function fetchUser() {
    try {
      if (token.value) {
        const userData = await getUserInfo(token.value);
        user.value = userData;
        localStorage.setItem('userData', JSON.stringify(userData));
        return userData;
      }
    } catch (error) {
      console.error('获取用户信息失败:', error);
      logout();
    }
  }
  
  function logout() {
    clearLoginInfo();
  }
  
  // 初始化时检查登录信息是否过期
  const isExpired = checkLoginExpiry();
  
  // 如果登录信息过期，清除所有登录信息
  if (isExpired) {
    clearLoginInfo();
  } else {
    // 从localStorage加载登录信息
    token.value = localStorage.getItem('token') || '';
    role.value = localStorage.getItem('role') || '';
    rememberMe.value = localStorage.getItem('rememberMe') === 'true';
    
    // 加载用户信息
    const userDataStr = localStorage.getItem('userData');
    if (userDataStr) {
      try {
        user.value = JSON.parse(userDataStr) as User;
      } catch (error) {
        console.error('解析用户信息失败:', error);
        user.value = null;
      }
    }
    
    // 如果有token但没有用户信息，则尝试获取用户信息
    if (token.value && !user.value) {
      fetchUser();
    }
  }

  return {
    token,
    role,
    user,
    rememberMe,
    isAuthenticated,
    login,
    fetchUser,
    logout,
  };
});
